import sys

from astropy.io import fits as pyfits
from astropy.visualization.interval import ZScaleInterval
from skimage import data, exposure, img_as_float
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
from astropy.visualization import simple_norm
# import Image,ImageFont,ImageDraw
import skimage as image
from pylab import *
import numpy as np
from astropy.wcs import WCS


def circle_points(RN, center, radius):
    radians = np.linspace(0, 2 * np.pi, RN)
    print("============")
    print(center[1])
    print(center[0])
    c = center[1] + radius * np.cos(radians)  # polar co-ordinates
    r = center[0] + radius * np.sin(radians)
    #print(np.array([c, r]).T)
    return np.array([c, r]).T


def cutImage(fullimage, xmin, xmax, ymin, ymax, otname):
    newimg_data = []
    fullimage = fullimage
    print(fullimage)
    xmin = xmin
    xmax = xmax
    ymin = ymin
    ymax = ymax
    otname = otname
    #print(fullimage)
    #print(xmin)
    #print(xmax)
    #print(ymin)
    #print(ymax)

    # cutimage = "aa.png"
    cutimage = fullimage[0:-4] + ".png"
    print(f' cutimage is {cutimage}')

    with pyfits.open(fullimage) as hdul:
        #hdul.info()
        hdul.verify('fix')
        img_data = np.array(hdul[0].data)
        wcs = WCS(hdul[0].header)
        #print(img_data)
        print(xmin)
        print(xmax)
        print(ymin)
        print(ymax)
        # print(len(img_data))
        # print(img_data.shape)
        newimg_data = img_data[xmin:xmax, ymin:ymax]
        # print(newimg_data)
        print("@@@@@@@@@@@@@@@@@")
        print(len(newimg_data))
        print(newimg_data.shape)
        
        pyfits.writeto(cutimage, newimg_data, header=None, overwrite=True)

        interval = ZScaleInterval()
        vmin, vmax = interval.get_limits(newimg_data)
        print(vmin)
        print(vmax)
        points = circle_points(200, [50, 50], 3)[:-1]
        # plt.subplot(1, 1, 1)
        fig = plt.gcf()
        #plt.axis('off')
        #fig.set_size_inches(7.0 / 3, 7.0 / 3)
        #plt.gca().xaxis.set_major_locator(plt.NullLocator())
        #plt.gca().yaxis.set_major_locator(plt.NullLocator())
        #plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
        #plt.margins(0, 0)
        plt.subplot(projection=wcs)
        plt.imshow(newimg_data, cmap=plt.cm.gray, vmin=vmin, vmax=vmax, origin='lower', aspect='equal')
        plt.plot(points[:, 0], points[:, 1], '-r', lw=1)
        plt.text(50, 50, otname, fontsize=20, color="white", verticalalignment="bottom", horizontalalignment="center")
        """
        points = circle_points(200, [20, 20], 6)[:-1]
        plt.subplot(1,2,2)
        plt.imshow(newimg_data, cmap=plt.cm.hot, vmin=vmin, vmax=vmax, origin='lower')
        plt.plot(points[:,0], points[:,1], '-b', lw=1)
        plt.text(20, 20, s='1', fontsize=20,color="black", verticalalignment="bottom", horizontalalignment="center")
        #plt.colorbar()
        """
        dir_data = sys.path[0]  #get the absolute path for current directory.
        #plt.savefig(dir="/disk2/test/xlp", fname=cutimage, format='png', dpi=300)
        #plt.savefig(dir=dir_data, fname=cutimage, format='png', dpi=300)
        plt.savefig(fname=cutimage, format='png', dpi=100)

        #plt.show()



if __name__ == "__main__":
    #img = "G171013_C05906_0696.fit"
    img = sys.argv[1]
    xmin = int(sys.argv[2])
    xmax = int(sys.argv[3])
    ymin = int(sys.argv[4])
    ymax = int(sys.argv[5])
    otname = sys.argv[6]
    print(img)
    print(xmin)
    print(xmax)
    print(ymin)
    print(ymax)
    cutImage(fullimage=img, xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, otname=otname)

